package com.lx.lxsql;

//说明: 我的数据库

import com.lx.lxsql.entity.StatementInformation;
import com.lx.lxsql.execute.Execute;
import com.lx.lxsql.execute.ExecuteUtil;
import com.lx.util.LX;

import java.io.*;
import java.util.*;


/**{ ylx } 2021/9/12 20:59 */
public class LXSQL {

    private static final String ERRMSG="脚本错误!";
    //说明: 初始化方法
    /**{ ylx } 2021/9/12 21:02 */
    public void init(){

    }
    public static void main(String[]args) throws Exception {
//        System.out.println(EXECUTES);
        String sql = "create   table table1(" +
                "aa decimal(123,10) not null default '213''''##@2' comment '1'" +
                ",primary key(aa,b)"+
                ",b varchar(23)" +
                ")";
        long t = System.currentTimeMillis();
        LXSQL lxdb = new LXSQL();
        List<String> ls = new ArrayList<>();
//        for (int i = 0; i < 100; i++) {
        Object o = lxdb.execSql(sql);
//        System.out.println(o);
//            ls.add("a"+i+o);
//        }
//        System.out.println(System.currentTimeMillis()-t);
//        writeBuffered(ls);
    }

    //说明: 执行脚本并返回结果
    /**{ ylx } 2021/9/12 21:05 */
    public Object execSql(String sql) throws Exception {
        if(sql == null){
            LX.exMsg("脚本不能为空!");
        }
        LinkedList<StatementInformation> sis = new LinkedList<>();
        StatementInformation.parseSqlnList(sql.length()>20?sql.substring(0,20):sql,sis);
        LX.exObj(sis,ERRMSG+sql);
        sis.forEach(v->{v.setTxt(v.getTxt().toLowerCase());});
//        System.out.println(sis);
        for (Execute execute : Execute.getEXECUTES()) {
            if (execute.matching(sis)){
                sis = new LinkedList<>();
                StatementInformation.parseSqlnList(sql,sis);
                return execute.exec(new ExecuteUtil(sis));
            }
        }
        LX.exMsg(ERRMSG+sql);
        return null;
    }




    private static void writeBuffered(List records) throws IOException {
        File file = new File("foo.txt");
        try {
            FileWriter writer = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(writer, 1048576);
            System.out.print("Writing buffered (buffer size: " + 1048576 + ")... ");
            write(records, bufferedWriter);
        } finally {
        }
    }

    private static void write(List<String> records, Writer writer) throws IOException {
        long start = System.currentTimeMillis();
        for (String record : records) {
            writer.write(record);
        }
        writer.flush();
        writer.close();
        long end = System.currentTimeMillis();
        System.out.println((end - start) / 1000f + " seconds");
    }



}
